package com.maikang.exammall.api;

import com.maikang.exammall.entity.Region;
import com.maikang.exammall.entity.dto.ResponseDTO;
import com.maikang.exammall.exception.BadRequestException;
import com.maikang.exammall.service.RegionService;
import lombok.extern.log4j.Log4j2;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.maikang.exammall.entity.constant.ApiCacheKeyConstant.regionApiKey;

@RestController
@Log4j2
@RequestMapping("/api/regions")
public class RegionController extends DictionaryController<Region, Long, RegionService> {

    @Cacheable(value = regionApiKey, key = "'findRegions:payload:'+#parentId+#level")
    @GetMapping
    public ResponseDTO<List<Region>> findRegions(@RequestParam(value = "level", required = false) Integer level, @RequestParam(value = "parentId", required = false) Long parentId) {
        List<Region> regions;
        if (parentId != null) {
            regions = service.findByParentId(parentId);
        } else if (level != null) {
            regions = service.findByLevel(level);
        } else {
            throw new BadRequestException("params must include level or parentId");
        }
        return ResponseDTO.ok(regions);
    }
}
